import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
    Text,
    TouchableOpacity,
    TouchableHighlight,
    TouchableNativeFeedback,
    TouchableWithoutFeedback
} from 'react-native';
import _ from 'lodash'

/**
 * 可点击视图
 *
 *  */
class TouchableView extends Component {
    static propTypes = {
        type: PropTypes.oneOf(['Opacity', 'Highlight', 'NativeFeedback', 'WithoutFeedback', 'Text']),
        label: PropTypes.object,
        children: PropTypes.any
    };
    constructor(props) {
        super(props);
        this.handleLock = false;
    }
    shouldComponentUpdate(nextProps, nextState) {
        return !(_.isEqual(this.props, nextProps) && _.isEqual(this.state, nextState));
    }
    componentWillUnmount() {
        this.handleTimeout && clearTimeout(this.handleTimeout);
    }
    handlePress = args => {
        // 防止重复点击
        if (this.handleLock) {
            return false;
        }
        this.handleLock = true;
        const passProps = { ...this.props };
        const originOnPress = passProps.onPress;

        if (originOnPress) {
            originOnPress(args);
        }

        this.handleTimeout = setTimeout(() => {
            this.handleLock = false;
        }, 300);
    };

    render() {
        const passProps = { ...this.props };

        if (this.props.type === 'Highlight') {
            return (
                <TouchableHighlight {...passProps} onPress={args => this.handlePress(args)}>
                    {this.props.children}
                </TouchableHighlight>
            );
        } else if (this.props.type === 'NativeFeedback') {
            return (
                <TouchableNativeFeedback {...passProps} onPress={args => this.handlePress(args)}>
                    {this.props.children}
                </TouchableNativeFeedback>
            );
        } else if (this.props.type === 'WithoutFeedback') {
            return (
                <TouchableWithoutFeedback {...passProps} onPress={args => this.handlePress(args)}>
                    {this.props.children}
                </TouchableWithoutFeedback>
            );
        } else if (this.props.type === 'Text') {
            return <Text {...passProps} onPress={args => this.handlePress(args)} />;
        } else {
            return (
                <TouchableOpacity {...passProps} onPress={args => this.handlePress(args)}>
                    {this.props.children}
                </TouchableOpacity>
            );
        }
    }
}

export default TouchableView;
